package server.test;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.timeout.IdleStateHandler;
import server.common.code.NettyMessageDecoder;
import server.common.code.NettyMessageEncoder;
import server.common.handler.HeartBeatRespHandler;
import server.common.handler.LoginAuthRespHandler;

/**
 * Created by xiangliyou on 17-9-22.
 *
 * @DESCRIPTION 服务端测试
 */
public class NettyServer {
    //等待心跳包的时间 单位 s, 一定要比客户端的长
    private static final int WAIT_HEART_BEAT_INTERVAL = 5;

    public static void main(String[] args) {
        NioEventLoopGroup bossGroup = new NioEventLoopGroup(1);
        NioEventLoopGroup workGroup = new NioEventLoopGroup(4);
        try {
            ServerBootstrap bootstrap = new ServerBootstrap();
            bootstrap
                    .group(bossGroup, workGroup)//
                    .option(ChannelOption.SO_BACKLOG, 1024)//
                    .channel(NioServerSocketChannel.class)//
                    .childHandler(new ServerChannelInitializer());//

            Channel ch = bootstrap.bind(12345).sync().channel();
            ch.closeFuture().sync();
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            bossGroup.shutdownGracefully();
            workGroup.shutdownGracefully();
        }
    }

    /**
     * 事件的处理器
     */
    private static class ServerChannelInitializer extends ChannelInitializer<SocketChannel> {

        @Override
        protected void initChannel(SocketChannel socketChannel) throws Exception {
            ChannelPipeline p = socketChannel.pipeline();
            //开启读写超时
            p.addLast(new IdleStateHandler(0, 0, WAIT_HEART_BEAT_INTERVAL));
            //自定义的解码器
            p.addLast("NettyMessageDecoder", new NettyMessageDecoder(Integer.MAX_VALUE, 4, 4, -8, 0));
            //自定义的编码器
            p.addLast("NettyMessageEncoder", new NettyMessageEncoder());
            //登录时握手请求的处理
            p.addLast("LoginAuthRespHandler", new LoginAuthRespHandler());
            //心跳处理——应答
            p.addLast("HeartBeatRespHandler", new HeartBeatRespHandler());
            //业务处理
            p.addLast("ServerHandler", new ServerHandler());
        }
    }
}